<?php
include("classes/GasPrice.php");
include("classes/GasRecord.php");


function initDB(){
/* Get Sectors from session */
    if(! isset($_SESSION['databaseURL'])){
           retreiveGasType();
        }
    $databaseURL = $_SESSION['databaseURL'];
    $databaseUName = $_SESSION['databaseUName'];
    $databasePWord = $_SESSION['databasePWord'];
    $databaseName = $_SESSION['databaseName'];

    $connection = mysql_connect($databaseURL,$databaseUName,$databasePWord);
        //or die ("Error while connecting to host");
    $db = mysql_select_db($databaseName,$connection);
        //or die ("Error while connecting to database");
    return $connection;
}

function retreiveGasType(){
    include("conf/conf.php");
    $dbConf = new AAConf();
    $databaseURL = $dbConf->get_databaseURL();
    $databaseUName = $dbConf->get_databaseUName();
    $databasePWord = $dbConf->get_databasePWord();
    $databaseName = $dbConf->get_databaseName();

        //Set DB Info. in-session
    $_SESSION['databaseURL']=$databaseURL;
    $_SESSION['databaseUName']=$databaseUName;
    $_SESSION['databasePWord']=$databasePWord;
    $_SESSION['databaseName']=$databaseName;


    $connection = mysql_connect($databaseURL,$databaseUName,$databasePWord);
        // or die ("Error while connecting to localhost");
    $db = mysql_select_db($databaseName,$connection);
        //or die ("Error while connecting to database");

    $rowArray;
    $rowID = 0;
    $query = "SELECT * FROM GasPrice";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result)){
            $gasPrice=new GasPrice();
            $gasPrice->set_Name($row['Name']);
            $gasPrice->set_Price($row['Price']);
            $gasPrice->set_GID($row['GID']);
            $rowArray[$rowID] = $gasPrice;
            $rowID = $rowID +1;
        }

        //Update the session with the sectors.
    $_SESSION['GasPriceNames']=$rowArray;
    mysql_close($connection);
}


/*
DB Closing method.
Pass the connection variable
obtained through initDB().
*/
function closeDB($connection){
    mysql_close($connection);
}


function commitRecord($gasStationName,$amount,$gasType,$price,$time,$mileage){
    $connection = initDB();

        //Update Guest Table
    $query2 = "insert into GasRecord(gasstationname,time,gid,totalprice,amount,mileage) values('".$gasStationName."','".$time."','".$gasType."','".$price."','".$amount."','".$mileage."')";
    $result2 = mysql_query($query2);
//        or die ("Query Failed ".mysql_error());

    closeDB($connection);
}

function getRecords(){
    $connection = initDB();
    $query; 
    $query = "select gasstationname, time, totalprice, amount,mileage,name,price from GasRecord as gr, GasPrice as gp where gp.gid=gr.gid order by time;";

    $result = mysql_query($query);
        //or die ("Query Failed ".mysql_error());
    $recordArray;
    $rowID = 0;
    while($row = mysql_fetch_array($result)){
            $gasPrice=new GasPrice();
            $gasPrice->set_Name($row['name']);
            $gasPrice->set_Price($row['price']);

            $record=new GasRecord();
            $record->set_GasStationName($row['gasstationname']);
            $record->set_Time($row['time']);
            $record->set_TotalPrice($row['totalprice']);
            $record->set_Amount($row['amount']);
            $record->set_Mileage($row['mileage']);
            $record->set_GasPrice($gasPrice);
            $recordArray[$rowID] = $record;
            $rowID = $rowID +1;
        }

    closeDB($connection);
    return $recordArray;
}

function getAverageOilWear($record,$next){
    if(!isset($next)){
        return "";
    }
    $intervalMileAge=$next->get_Mileage()-$record->get_Mileage();
    return $record->get_Amount()*100/$intervalMileAge;
}



//Array ( ["baiyun"] => 8.5 ["fujiazhuang"] => 9.5)
function getStationOilWear(){
    $recordArray = getRecords();
    $result = array();
    
    for($index=0;$index < count($recordArray)-1;$index++){
        $record = $recordArray[$index];

        $oilWear=getAverageOilWear($record,$recordArray[$index+1]);
        $record->set_OilWear($oilWear);

        $stationName=$record->get_GasStationName();

        if(!array_key_exists($stationName, $result)){
             $result[$stationName] = array();
        }
        array_push($result[$stationName],  $record->get_OilWear());
     }
     //Array ( ["baiyun"] => {8.2,8.1} ["fujiazhuang"] => {7.9,7.4})
     foreach($result as $key => $value){
        $result[$key]=array_sum($value)/count($value);
     }
     //Array ( ["baiyun"] => 8.5 ["fujiazhuang"] => 9.5)
    
     return $result;
}

function getStationChineseName($name){
    $maps["beigangqiao"]="北岗桥";
    $maps["baiyun"]="白云山";
    $maps["fujiazhuang"]="付家庄";
    $maps["hongqi"]="红旗路";
    $maps["nandating"]="南大庭";
    $maps["shikuilu"]="石葵路";
    $maps["xijiao"]="西郊";
    $maps["laohutan"]="老虎滩";
    return $maps[$name];
}

function getCostByMonth(){
    $connection = initDB();
    $query;
    $query = "SELECT substring(time,3,5) as month,sum(totalPrice) as cost FROM GasRecord group by  substring(time,3,5);";

    $result = mysql_query($query);
        //or die ("Query Failed ".mysql_error());
    $items=array();
    $rowID = 0;
    while($row = mysql_fetch_array($result)){
            $items[$row['month']]=(double)$row['cost'];
            $rowID = $rowID +1;
        }

    closeDB($connection);
    return $items;
}


function getGasTrend(){
    $connection = initDB();
    $query;
    $query = "SELECT substring(date,1,10) as month, price FROM GasPrice;";

    $result = mysql_query($query);
        //or die ("Query Failed ".mysql_error());
    $items=array();
    $rowID = 0;
    while($row = mysql_fetch_array($result)){
            $items[$row['month']]=(double)$row['price'];
            $rowID = $rowID +1;
        }

    closeDB($connection);
    return $items;
}


//TEST
//$record1=new GasRecord();
//$record1->set_GasStationName("baiyun");
//$record1->set_OilWear(8);
//$record2=new GasRecord();
//$record2->set_GasStationName("fujiangzhuang");
//$record2->set_OilWear(10);
//
//$record3=new GasRecord();
//$record3->set_GasStationName("baiyun");
//$record3->set_OilWear(9);
//$record4=new GasRecord();
//$record4->set_GasStationName("fujiangzhuang");
//$record4->set_OilWear(11);
//
// $result = array();
// $userlist=array($record1,$record2,$record3,$record4);
//
// foreach($userlist as $user){
// if(!array_key_exists($user->get_GasStationName(), $result)){
//     $result[$user->get_GasStationName()] = array();
// }
//  array_push($result[$user->get_GasStationName()],  $user->get_OilWear());
// }
//
// foreach($result as $key => $value){
//      echo $key . " " . array_sum($value)/count($value) ;
//
//      $result[$key]=array_sum($value)/count($value);
// }
// print_r("\n\r");
//
// print_r(array_keys($result));
//
// $result=getStationOilWear();
// print_r("\n\r--------------------------------");
// print_r($result);
//
// foreach($result as $key => $value){
//      echo "_______________".$key . " " . $value ;
//
//
// }


?>